from datetime import datetime
from typing import Optional
from uuid import UUID, uuid4

from bisheng.database.base import session_getter
from bisheng.database.models.base import SQLModelSerializable
from sqlalchemy import Column, DateTime, String, Text, text, desc
from sqlmodel import Field, SQLModel


class FaultWorkOrderBase(SQLModelSerializable):
    id: UUID = Field(nullable=False, primary_key=True, description='唯一ID')
    group_id: str = Field(sa_column=Column(String(length=255), default=''), description='告警记录ID')
    type: str = Field(sa_column=Column(String(length=255), default=''), description='类型')
    child_type: str = Field(sa_column=Column(String(length=255), default=''), description='细分类型')
    status: str = Field(sa_column=Column(String(length=255), default=''), description='状态')
    maintenance_department: str = Field(sa_column=Column(String(length=255), default=''), description='维护部门')
    repair_department: str = Field(sa_column=Column(String(length=255), default=''), description='报修部门')
    kind: str = Field(sa_column=Column(String(length=255), default=''), description='分类')
    professional_kind: str = Field(sa_column=Column(String(length=255), default=''), description='专业分类')
    fault_level: str = Field(sa_column=Column(String(length=255), default=''), description='故障等级')
    self_inspection: str = Field(sa_column=Column(String(length=255), default=''), description='自检')
    order_file_path: str = Field(sa_column=Column(String(length=255), default=''), description='工单文件路径')
    code: str = Field(sa_column=Column(String(length=255), default=''), description='编号')
    chat_id :str = Field(sa_column=Column(String(length=255), default=''), description='chat_id')
    plan_start_time: Optional[datetime] = Field(sa_column=Column(DateTime, nullable=False, server_default=text('CURRENT_TIMESTAMP')),
                            description='计划开始时间')
    plan_end_time: Optional[datetime] = Field(sa_column=Column(DateTime, nullable=False, server_default=text('CURRENT_TIMESTAMP')),
                          description='计划结束时间')
    create_time: Optional[datetime] = Field(
        sa_column=Column(DateTime, nullable=False, server_default=text('CURRENT_TIMESTAMP')))


class FaultWorkOrder(FaultWorkOrderBase, table=True):
    id: UUID = Field(default_factory=uuid4, primary_key=True, unique=True)


class FaultWorkOrderDao:
    @staticmethod
    def create_fault_work_order(fault_work_order: FaultWorkOrder) -> FaultWorkOrder:
        """
        创建新的故障工单
        :param fault_work_order: FaultWorkOrder 对象
        :return: 创建并保存到数据库的 FaultWorkOrder 对象
        """
        with session_getter() as session:
            # 确保 fault_work_order 有一个 UUID
            if not fault_work_order.id:
                fault_work_order.id = uuid4()

            session.add(fault_work_order)
            session.commit()
            session.refresh(fault_work_order)
            return fault_work_order

    @staticmethod
    def get_fault_work_order_by_id(id):
        with session_getter() as session:
            if isinstance(id, str):
                id = UUID(id)
            query = session.query(FaultWorkOrder).filter(FaultWorkOrder.id == id)
            return query.first()

    @staticmethod
    def get_lastest_order():
        with session_getter() as session:
            query = session.query(FaultWorkOrder).order_by(desc(FaultWorkOrder.create_time))
            return query.first()

    @staticmethod
    def get_lastest_order_by_group_id(group_id):
        with session_getter() as session:
            query = session.query(FaultWorkOrder).filter(FaultWorkOrder.group_id == group_id).order_by(
                desc(FaultWorkOrder.create_time))
            return query.first()

    @staticmethod
    def get_fault_work_order_by_group_id_chat_id(group_id, chat_id):
        with session_getter() as session:
            query = session.query(FaultWorkOrder).filter(FaultWorkOrder.chat_id == chat_id,
                                                          FaultWorkOrder.group_id == group_id).order_by(
                desc(FaultWorkOrder.create_time))
            return query.first()



